package org.rcgwt.configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.GeneratorContext;

/**
 * A tool object thats manage configuration file path by priority. That returns
 * a ordered list of file path by priority. Like : [path];[priority]
 * 
 * @author Elian ORIOU
 * 
 */

public class ConfigurationManager {

	private final GeneratorContext context;
	private Map<Integer, String> configurations;

	private final String propertyName;

	public ConfigurationManager(GeneratorContext generatorContext,
			String propertyName)
			throws BadPropertyValueException {
		this.context = generatorContext;
		this.propertyName = propertyName;
		getConfigurations();
	}

	private void getConfigurations() throws BadPropertyValueException {
		if (context == null || propertyName == null) {
			return;
		}
		configurations = new HashMap<Integer, String>();
		List<String> names = context.getPropertyOracle()
				.getConfigurationProperty(propertyName).getValues();

		for (String s : names) {
			if (s.matches(".+\\Q;\\E[0-9]+") == true) {
				int priority = Integer.parseInt(s
						.substring(s.lastIndexOf(";") + 1));
				String filePath = s.substring(0, s.lastIndexOf(";"));
				configurations.put(priority, filePath);
			} else {
				configurations.put(0, s);
			}
		}
	}

	public List<String> getOrderedConfigurations() {
		if (configurations.isEmpty() == true) {
			return Collections.emptyList();
		}

		List<String> filePaths = new ArrayList<String>();
		List<Integer> priorities = new ArrayList<Integer>();

		priorities.addAll(configurations.keySet());
		Collections.sort(priorities);
		for (int p : priorities) {
			filePaths.add(configurations.get(p));
		}
		return filePaths;
	}
}
